package com.mengfou;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 梦否
 * @date 2025/07/05 14:11
 */
public class HotFixHelper {

    public static void hotFix(LogProxy logProxy, String methodName, String tag, String s, ClassLoader classLoader) {
        System.out.println("-- hot fix start. class: " + logProxy.getClass().getName());
        accessMethod(logProxy, methodName, tag, s, classLoader);
        System.out.println("-- hot fix end.   class: " + logProxy.getClass().getName());
    }

    public static void accessMethod(LogProxy logProxy, String methodName, String tag, String s, ClassLoader classLoader) {
        try {
            String className = findClassName();
            Class<?> aClass = Class.forName(className, true, classLoader);
            Field proxy = aClass.getDeclaredField("proxy");
            Field classLoaderField = aClass.getDeclaredField("classLoader");
            classLoaderField.setAccessible(true);
            proxy.setAccessible(true);
            Object o = aClass.newInstance();
            classLoaderField.set(o, classLoader);
            proxy.set(o, logProxy);
            Method declaredMethod = aClass.getDeclaredMethod(methodName, String.class, String.class);
            declaredMethod.setAccessible(true);
            declaredMethod.invoke(o, tag, s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String findClassName() {
        return "com.mengfou.test.Demo";
    }
}
